import Konva from "konva";
import { KeyListener } from "../../utils/KeyListener";
import type { TransformerManager } from "../handler/TransformerManager";

export interface GraphOptions {
    height: number;
    width: number;
    x: number;
    y: number;
    fill?: string;
    stroke?: string;
    strokeWidth?: number;
    draggable?: boolean;
}

abstract class BaseGraph {
    protected options: GraphOptions;
    protected node: Konva.Shape | null = null; // 使用 Konva.Shape 明确节点类型

    constructor(options: GraphOptions) {
        this.options = {
            fill: "transparent", // 默认填充颜色
            stroke: "#000",      // 默认边框颜色
            strokeWidth: 1,      // 默认边框宽度
            draggable: false,    // 默认不可拖拽
            ...options,          // 合并用户传入的选项
        };
    }

    // 抽象方法，子类需要实现具体绘制逻辑
    abstract draw(layer: Konva.Layer): void;

    // 更新图形属性
    update(attrs: Partial<GraphOptions>): void {
        if (this.node) {
            this.node.setAttrs(attrs);
            Object.assign(this.options, attrs); // 同步更新 options
        }
    }

    // 销毁图形
    destroy(): void {
        if (this.node) {
            this.node.destroy();
            this.node = null;
        }
    }

    // 通用事件绑定方法
    bindEvent(eventType: string, callback: (e: Konva.KonvaEventObject<Event>) => void): void {
        if (this.node) {
            this.node.on(eventType, callback);
        }
    }

    // 默认的事件绑定逻辑，子类可以扩展或覆盖
    protected bindEvents(
        layer: Konva.Layer,
        selectedShapes: Konva.Node[],
        transformerManager: TransformerManager,
        ctrlKeyListener: KeyListener,
        stage: Konva.Stage
    ): void {
        if (!this.node) {
            // 点击舞台其他地方取消选中
            stage.on('click', () => {
                transformerManager.clear();
                selectedShapes = [];
                layer.batchDraw();
            });
            return;
        }

        // 点击事件绑定
        this.bindEvent("click", (e) => {
            e.cancelBubble = true; // 防止事件冒泡到舞台点击事件

            if (ctrlKeyListener.isCtrlPressed()) {
                // Ctrl 多选逻辑
                if (selectedShapes.includes(this.node!)) {
                    selectedShapes = selectedShapes.filter((shape) => shape !== this.node);
                } else {
                    selectedShapes.push(this.node!);
                }
            } else {
                // 单选逻辑
                selectedShapes = [this.node!];
            }

            // 绑定 Transformer 到选中的图形
            transformerManager.bindToShapes(selectedShapes);
            layer.batchDraw();
        });

        // 示例：绑定拖拽事件（可扩展）
        this.bindEvent("dragmove", (e) => {
            console.log("Node is moving:", e.target);
        });

        // 将节点添加到图层
        layer.add(this.node);
    }
}

export default BaseGraph;
